
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_test1/api/http/http.dart';
import 'package:flutter_test1/api/http/http_request.dart';
import 'package:flutter_test1/bean/BaseBean.dart';
import 'package:flutter_test1/bean/BaseObject.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class HomeWidget extends StatefulWidget{

  @override
  State<StatefulWidget> createState() {
    return _HomeWidget();
  }

}

class _HomeWidget extends State<HomeWidget> with SingleTickerProviderStateMixin{

  final List<String> swiper_images = ["assets/images/home_banner1.png","assets/images/home_banner2.png"];
  final List tabs = ["tab1","tab2"];
  late TabController tabController;

  @override
  void initState() {
    super.initState();
    tabController = TabController(length: tabs.length, vsync: this);
    // print("屏幕高度：" + MediaQuery.of(context).size.height.toString());
    // print("tabBar高度：" + tabBar_key.currentContext!.size!.height.toString());
    // print("状态栏高度：" + MediaQueryData.fromWindow(window).padding.top.toString());

    tabController.addListener(() {

    });
  }

  @override
  Widget build(BuildContext context) {
    return NestedScrollView(
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled){
        return <Widget>[
          SliverList(
            delegate: SliverChildBuilderDelegate((context,index){
              if(index == 0){
                return AppBar(
                  title: Text("首页",style: TextStyle(color: Colors.white),),
                  leading: null,
                  centerTitle: true,
                  primary:false,
                );
              }
              if(index == 1){
                return Container(
                  width: double.infinity,
                  height: 170.0,
                  child: new Swiper(
                    autoplay: true,
                    itemBuilder: (BuildContext context,int index){
                      return new Image.asset(swiper_images[index],fit: BoxFit.cover);
                    },
                    itemCount: swiper_images.length,
                    pagination: new SwiperPagination(),
                    onTap: (index){

                    },
                  ),
                );
              }
            })
          ),
          SliverPersistentHeader(
            delegate: SliverTabBarDelegate(
                TabBar(
                  tabs: tabs.map((e) => Tab(text: e)).toList(),
                  controller: tabController,
                  indicatorColor: Colors.white,
                )
            ),
            pinned: true,
          ),
        ];
      },
      body: Container(
        child: TabBarView(
          controller: tabController,
          children: [
            TabNews(),//内容列表
            TabCustom(),//内容列表
          ],
        ),
      ),
    );
  }
}

class SliverTabBarDelegate extends SliverPersistentHeaderDelegate{

  final TabBar widget;

  const SliverTabBarDelegate(this.widget)
      : assert(widget != null);


  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      decoration: BoxDecoration(
          color: Colors.blue,
          boxShadow: [
            BoxShadow(
                color: Colors.black54,
                offset: Offset(2.0,2.0),
                blurRadius: 4.0
            )
          ]
      ),
      child:widget,
    );
  }

  @override
  double get maxExtent => widget.preferredSize.height;

  @override
  double get minExtent => widget.preferredSize.height;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate
      ) {
    return false;
  }

}

class TabNews extends StatefulWidget{

  TabNews({Key?key}) :super(key: key);

  @override
  State<StatefulWidget> createState() => _TabNews();
}

class _TabNews extends State<TabNews> with AutomaticKeepAliveClientMixin{
  List<BaseObject> list_news = [];
  int pageSize = 5;
  int page = 1;
  late Future get_news;
  EasyRefreshController easyRefresh_controller = EasyRefreshController();

  @override
  void initState() {
    super.initState();
    get_news = getData(true);
  }

  Future refresh() async {
    page = 1;
    get_news = await getData(true);
  }

  Future loadMore() async {
    page++;
    get_news = await getData(false);
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      builder: _futureBuilder,
      future: get_news,
    );
  }

  Widget _futureBuilder(BuildContext context,AsyncSnapshot snapshot){
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.active:
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.waiting:
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');
        //list_news = snapshot.data.data.data.list;
        return EasyRefresh(
          controller: easyRefresh_controller,
          enableControlFinishLoad: true,
          enableControlFinishRefresh: true,
          header: ClassicalHeader(
            refreshText: "下拉刷新",
            refreshReadyText: "松手刷新",
            refreshingText: "正在刷新",
            refreshedText: "刷新完成",
            showInfo: false,
            textColor: Color(0xFF999999),
          ),
          footer: ClassicalFooter(
              loadedText: "上拉加载",
              loadReadyText: "松手加载",
              loadingText: "正在加载",
              noMoreText: "没有更多数据了",
              showInfo: false,
              textColor: Color(0xFF999999),
          ),
          onRefresh: () async {
            await getData(true);
          },
          onLoad: () async {
            page++;
            await getData(false);
          },
          child: ListView(
            children: list_news.map((item) => Container(
              child: Padding(padding: EdgeInsets.all(20.0),
                child:  Row(
                  children: [
                    Image.network(item.articleImages,fit: BoxFit.cover,width: 60, height: 60,),
                    Expanded(
                        flex: 1,
                        child: Padding(
                          padding: EdgeInsets.only(left: 20.0),
                          child: Text(item.articleTitel,maxLines: 1,overflow:TextOverflow.ellipsis),
                        )
                    )
                  ],
                ),
              ),
            )).toList(),
          )
        );
      default:
        return Container();
    }
  }

  Future getData(bool isRefresh) async {
    YYResultModel<BaseBean> result = await SRHttpRequest.getInstance().newsList(defaultCurrent: page,pageSize: pageSize);
    if(result.checkRequestSuccess()){
      if(isRefresh){
        list_news = result.data!.data!.list!;
      }else{
        list_news.addAll(result.data!.data!.list!);
      }
      if(list_news.length >= result.data!.data!.total){
        if(isRefresh){
          easyRefresh_controller.finishRefresh(success:true,noMore: true);
        }else{
          easyRefresh_controller.finishLoad(success:true,noMore: true);
        }
      }else{
        if(isRefresh){
          easyRefresh_controller.finishRefresh(success:true,noMore: false);
        }else{
          easyRefresh_controller.finishLoad(success:true,noMore: false);
        }
      }
      setState(() {

      });
    }
    return result;
  }

  @override
  bool get wantKeepAlive => true;
}

class TabCustom extends StatefulWidget{

  TabCustom({Key?key}) :super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _TabCustom();
  }
}

class _TabCustom extends State<TabCustom> with AutomaticKeepAliveClientMixin{
  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        Text("自定义布局"),
        Text("------------------------------------------------------------------------"),
        Text("---  -----  ----- ----------- ------------ -----                 -------"),
        Text("---  -----  ----- ----------- ------------ ------------- ---------------"),
        Text("----  ---  ------- --------- - ---------- -------------- ---------------"),
        Text("-----  -  --------- ------- --- -------- --------------- ---------------"),
        Text("------- ------------ ----- ----- ------ ---------------- ---------------"),
        Text("------- ------------- --- ------- ---- ----------------- ---------------"),
        Text("------- -------------- - --------- -- ------------------ ---------------"),
        Text("------- -------------- - --------- - ------------------- ---------------"),
        Text("------- --------------- ----------- -------------------- ---------------"),
        Text("-----------------------------------------------------------------------"),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  bool get wantKeepAlive => true;
}

abstract class WidgetCallBack{
  void callBack(bool isRefresh,bool noMore);
}